import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:shop/http/HttpUtil.dart';
import 'package:shop/route/my_route.dart';
import 'package:shop/shop/life/Index.dart';
import 'package:shop/shop/life/Regist.dart';
import 'Center.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';
class Login extends StatefulWidget {
  Login({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _Login createState() => _Login();
}

class _Login extends State<Login> {
  TextEditingController _unameController = new TextEditingController(); // 用户用户名从这里获取
  TextEditingController _pwdController = new TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text("欢迎登录"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
              child: TextFormField(
                // maxLines: 1,
                // maxLength: 12,
                obscureText: false,
                controller:_unameController ,
                decoration: InputDecoration(
                  hintText: "手机号码",
                  icon:  Icon(Icons.perm_identity),
                  labelText: "手机号码",
                ),
                validator: (val){
                  if(val.trim().length<1)
                    return "手机号码不能为空";
                  return null;
                },
                onSaved: (str) {
                  _unameController.text = str;//str为文本的内容值
                },
              ),
            ),
            Container(
              child: TextFormField(
                controller: _pwdController,
                // maxLines: 1,
                // maxLength: 12,
                obscureText: true,
                decoration: InputDecoration(
                  hintText: "密码至少6位",
                  icon:  Icon(Icons.https),
                  labelText: "密码",
                ),
                validator: (value) {
                  //RegExp reg = new RegExp(r'^\d{11}$');
                  // if (!reg.hasMatch(value)) {
                  //   return '请输入11位手机号码';
                  // }
                  if(value.trim().length<1)
                    return "密码不能为空";
                  return null;
                },
                onSaved: (str) {
                  print("密码是:${str}");
                  _pwdController.text = str;//str为文本的内容值
                  setState(() {

                  });
                },
              ),
            ),
            Container(
              child: RaisedButton(
                shape: RoundedRectangleBorder(),
                onPressed: () async {
                  // post提示用户名或密码为空，get提交可以登录
                  if(_unameController.text.trim().length<1)
                  {
                    Fluttertoast.showToast(
                        msg: "手机号不能为空",
                        toastLength: Toast.LENGTH_SHORT,
                        gravity: ToastGravity.BOTTOM,
                        timeInSecForIosWeb: 1,
                        backgroundColor: Colors.black45,
                        textColor: Colors.white,
                        fontSize: 16.0
                    );
                    return ;
                  }
                  if(_pwdController.text.trim().length<3)
                  {
                    Fluttertoast.showToast(
                        msg: "密码不能为空",
                        toastLength: Toast.LENGTH_SHORT,
                        gravity: ToastGravity.BOTTOM,
                        timeInSecForIosWeb: 1,
                        backgroundColor: Colors.black45,
                        textColor: Colors.white,
                        fontSize: 16.0
                    );
                    return ;
                  }
                  //Response response = await Dio().get("http://xllm.szghrj.com:8082/app/user/login",queryParameters:{"username":_unameController.text.trim(),"password":_pwdController.text.trim()});
                  //var x = json.decode(response.toString());
                  // 使用封装的方法发起请求，注意x的赋值
                  var x = await HttpUtil().get("/app/user/login?username=${_unameController.text.trim()}&password=${_pwdController.text.trim()}");
                  if(x['code']==200){
                    // Navigator.push() 带返回
                    // Navigator.pushReplacement() 不带返回
                    SharedPreferences prefs = await SharedPreferences.getInstance();
                    prefs.setString("userId", x['data']['userId']);//将用户ID存内存里
                    prefs.setString("userName", x['data']['userName']);//将用户名存内存里
                    prefs.setString("userJifen", x['data']['userIntegral'].toString());//将积分存内存里
                    prefs.setBool("isLogin", true);     // 已登录
                    MyRoute.replace(Index());
                    // Navigator.pushReplacement(
                    //     context,
                    //     MaterialPageRoute(
                    //         builder:(context)=>Index()
                    //     )
                    // );
                  }else{
                    Fluttertoast.showToast(
                        msg: "用户名或密码错误",
                        toastLength: Toast.LENGTH_SHORT,
                        gravity: ToastGravity.BOTTOM,
                        timeInSecForIosWeb: 1,
                        backgroundColor: Colors.black45,
                        textColor: Colors.white,
                        fontSize: 16.0
                    );
                  }
                },
                child: Text("登录",
                   ),
              ),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                GestureDetector(child: Text("立即注册"),
                onTap: (){
                  Navigator.pushReplacement(
                      context,
                      MaterialPageRoute(
                          builder:(context)=>Regist()
                      )
                  );
                },),
                Text("忘记密码")
              ],
            )
          ],
        ),
      ),
    );
  }
}